package com.example.shop_2305.search

import android.graphics.Color
import android.os.Bundle
import android.os.Handler
import android.view.LayoutInflater
import android.widget.TextView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.widget.SearchView
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.recyclerview.widget.GridLayoutManager
import com.alibaba.android.arouter.facade.annotation.Route
import com.blankj.utilcode.util.ToastUtils
import com.example.lib_base.mvvm.BaseActivity
import com.example.lib_base.room.AppDbUtils
import com.example.lib_base.room.KeyEntity
import com.example.shop_2305.R
import com.example.shop_2305.adapter.GoodsAdapter
import com.example.shop_2305.adapter.KeyAdapter
import com.example.shop_2305.databinding.ActivitySearchBinding
import com.google.android.material.chip.Chip
import java.util.Timer
import java.util.TimerTask
import kotlin.concurrent.timerTask

@Route(path = "/app/SearchActivity")
class SearchActivity : BaseActivity<ActivitySearchBinding,SearchViewModel>() {
    lateinit var goodsAdapter: GoodsAdapter
    var cid:Int = 0
    var keyword:String = ""
    var limit:Int = 10
    var news:Boolean = false
    var page:Int = 1
    var priceOrder:String = ""
    var salesOrder:String = ""
    lateinit var timer: Timer
    var handler = Handler()
    var index = 0//显示的是第几个关键词
    override fun initView() {
        //模拟关键词 每2秒切换一个
        val keys = mutableListOf("口红","茶叶","张徐")
        timer = Timer()
        timer.schedule(timerTask {
            handler.post {
                binding.sv.queryHint = keys[index]
                index++
                if(index>2){
                    index=0
                }
            }
        },0,2000)



        goodsAdapter = GoodsAdapter()
        binding.rvGoods.adapter = goodsAdapter
        binding.rvGoods.layoutManager = GridLayoutManager(this,2)

        //选择价格排序 （无序 "" 升序 asc  降序 desc ） 那么销量就没有顺序    选择销量排序  那么价格就没有顺序
        binding.tvPrice.setOnClickListener {
            if(priceOrder==""){
                //这是第一次点击
                priceOrder = "asc"
                binding.ivPrice.setImageResource(R.drawable.sort1)
            }else if(priceOrder=="asc"){
                //这是第二次点击
                priceOrder = "desc"
                binding.ivPrice.setImageResource(R.drawable.sort2)
            }else{
                //这是第三次点击
                priceOrder = ""
                binding.ivPrice.setImageResource(R.drawable.sort3)
            }

            salesOrder = ""
            binding.ivSale.setImageResource(R.drawable.sort3)
            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }

        binding.tvSale.setOnClickListener {
            if(salesOrder==""){
                //这是第一次点击
                salesOrder = "asc"
                binding.ivSale.setImageResource(R.drawable.sort1)
            }else if(salesOrder=="asc"){
                //这是第二次点击
                salesOrder = "desc"
                binding.ivSale.setImageResource(R.drawable.sort2)
            }else{
                //这是第三次点击
                salesOrder = ""
                binding.ivSale.setImageResource(R.drawable.sort3)
            }

            priceOrder = ""
            binding.ivPrice.setImageResource(R.drawable.sort3)
            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }
        //点击新品 ，文字变成红色  再次点击文字变回黑色
        binding.tvNew.setOnClickListener {
            if(news){
                //当前是新品  文字是红色  点击之后文字变回黑色
                binding.tvNew.setTextColor(Color.BLACK)
                news = false
            }else{
                binding.tvNew.setTextColor(Color.RED)
                news = true
            }
            viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
        }



        queryKey()//查询历史搜索记录
        binding.sv.setOnQueryTextListener(object:SearchView.OnQueryTextListener{
            override fun onQueryTextSubmit(query: String?): Boolean {
                //当点击回车按钮执行下方方法
                if(query!=null){
                    keyword = query
                    viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
                    AppDbUtils.getAppDb().getKeyDao().insert(KeyEntity(query))
                    queryKey()
                }
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                //文字发生变化时执行下方方法
                if(newText!=null){
                    keyword = newText
                    viewModel.goods(cid, keyword, limit, news, page, priceOrder, salesOrder)
                    ToastUtils.showLong(newText)
                }
                return false
            }
        })
        //清空所有
        binding.tvDeleteAll.setOnClickListener {
            AppDbUtils.getAppDb().getKeyDao().deleteAll()
            binding.cg.removeAllViews()
        }
    }

    private fun queryKey() {
        //查询数据库中的数据
        val list = AppDbUtils.getAppDb().getKeyDao().query()
        list.sortByDescending { it.keyword }
        list.reverse()
        //将之前展示的历史记录清空
        binding.cg.removeAllViews()
        if(list.size>0){
            list.forEach {it->
                //循环创建chip  数据库中有几条记录就创建几个chip
                val chip = LayoutInflater.from(this)
                    .inflate(R.layout.item_cg, null) as Chip
                //给对应的chip的文本设置内容
                chip.findViewById<TextView>(R.id.cg_name).text = it.keyword
                binding.cg.addView(chip)

                //点击chip,可实现再次搜索   关键词换成点击的这个
                chip.setOnClickListener { it1->
                    binding.sv.setQuery(it.keyword,true)
                }
                //点击chip上的关闭图标 实现删除历史记录
                chip.setOnCloseIconClickListener { it2->
                    AppDbUtils.getAppDb().getKeyDao().delete(it)
                    binding.cg.removeView(it2)
                }

            }
        }
    }

    override fun initData() {
            viewModel.goodsSuccess.observe(this){
                if(it.code==200){
                    goodsAdapter.data.clear()
                    goodsAdapter.data.addAll(it.data.list)
                    goodsAdapter.notifyDataSetChanged()
                }
            }
    }

    override fun getViewModel(): Class<SearchViewModel> = SearchViewModel::class.java

    override fun getLayout(): Int  = R.layout.activity_search

}